import constant from "@/common/constant.js";
import { TUIConversationService } from "@tencentcloud/chat-uikit-engine";


//跳转到聊天
function toChat(txCode) {
	getApp().globalData.chatTxCode = txCode;
	const conversationID = `C2C` + txCode;
	uni.$TUIKit.setMessageRead({
		conversationID: conversationID
	}).then(res => {
		const count = uni.$TUIKit.getTotalUnreadMessageCount();
		if (count > 0) {
			uni.setTabBarBadge({
				index: constant.messageIndex,
				text: '' + count
			})
		} else {
			uni.removeTabBarBadge({
				index: constant.messageIndex,
			})
		}
	});
	TUIConversationService.switchConversation(conversationID);
	uni.navigateTo({
		url: `/TUIKit/components/TUIChat/index?conversationID=${conversationID}`,
	});
}

function getConversationList(){
	return new Promise((resolve, reject)=>{
		uni.$TUIKit.getConversationList().then(res => {
			//处理小秘书---移动到首位
			let xiaomishu = {};
			let hasXiaomishu = false;
			res.data.conversationList.forEach((item, index) => {
				if('administrator'==item.userProfile.userID){
					item.userProfile.nick = "小秘书";
					item.userProfile.avatar = this.getImageUrl('logo.png');
					xiaomishu = item;
					hasXiaomishu = true;
					res.data.conversationList.splice(index, 1);
					return;
				}
			})
			if(hasXiaomishu){
				res.data.conversationList.unshift(xiaomishu);
			}
			resolve(res.data.conversationList)
			// this.conversationList = res.data.conversationList;
			console.log("this.conversationList: " + JSON.stringify(res.data.conversationList));
		}).catch(error => {
			reject(error)
		    console.warn('获取会话列表失败:', error);
		});
	})
}

export default {
	toChat,
	getConversationList
}